package com.xlserver.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xlserver.dao.*;
import com.xlserver.domain.*;
import com.xlserver.util.TimeUtil;
import com.xlserver.util.TokenUtil;
import com.xlserver.util.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CounselorService {
    @Autowired
    CounselorMapper counselorMapper;

    @Autowired
    ConsultationMapper consultationMapper;

    @Autowired
    LoginInfoMapper loginInfoMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    TimeUtil timeUtil;

    @Autowired
    ScheduleService scheduleService;

    @Autowired
    StateMapper stateMapper;

    @Autowired
    SupervisorBandCounselorMapper supervisorBandCounselorMapper;

    @Autowired
    SupervisorMapper supervisorMapper;

    /**
     *获取咨询师信息
     */
    public JSONObject getUserInfo(String username, String password) throws ParseException {
        JSONObject res = new JSONObject();
        if (!checkUsername(username)){
            res.put("result","1");
            return res;
        }
        QueryWrapper<Counselor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cUsername",username);
        Counselor counselor = counselorMapper.selectOne(queryWrapper);
        if (!checkPassword(counselor.getCid(),password)){
            res.put("result","2");
            return res;
        }
        Date date = new Date();
        res.put("result","3");
        res.put("id",counselor.getCid());
        res.put("username",counselor.getUsername());
        res.put("name",counselor.getName());
        res.put("todayStatus",scheduleService.getPersonTodayStatus(counselor.getCid()));
        res.put("isFree",timeUtil.isFree(counselor.getCid()));
        res.put("profilePhoto",counselor.getProfilePhoto());
        res.put("averageGrade",counselor.getAverageGrade());
        res.put("sumOfConsultation",timeUtil.sumOfConsultation(counselor.getCid()));
        res.put("todaySchedule",scheduleService.getCounselorWeekSchedule(counselor.getCid(),date));
        res.put("sumOfConsultationToday",timeUtil.sumOfConsultationToday(counselor.getCid()));
        res.put("timeOfConsultationToday",timeUtil.timeOfConsultationToday(counselor.getCid()));
        res.put("questsCompleted",counselor.getQuestsCompleted());
        res.put("theLastFour",lastConsultations(counselor.getCid()));
        res.put("token", TokenUtil.sign(""+counselor.getCid(), password));
        //在线
        stateMapper.update(null,new UpdateWrapper<State>().eq("id",counselor.getCid()).set("state",0));
        res.put("isOnline",true);
        return res;
    }
    /**
     * 修改咨询师个人信息
     */
    public boolean updateInfo(UserInfo info){
        UpdateWrapper<Counselor> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("cid",info.getUserId())
                .set("cProfilePhoto",info.getPhotoAddress())
                .set("cName",info.getName())
                .set("cGender",info.getGender())
                .set("cAge",info.getAge())
                .set("cIdNumber",info.getIdNumber())
                .set("cPhoneNum",info.getPhoneNum())
                .set("cEmail",info.getEmail());

        return counselorMapper.update(null,updateWrapper) == 1;
    }

    /**
     * 获取所有会话
     */
    public JSONArray getAllMsgs(int cid){
        List<Consultation> consultations = consultationMapper.selectList(
                new QueryWrapper<Consultation>().eq("cid",cid));
        JSONArray res = new JSONArray();
//        JSONObject averRank = new JSONObject();
//        averRank.put("averageRank",timeUtil.averageRank(consultations));
//        res.add(averRank);
        consultations.forEach(consultation -> {
            JSONObject msg = new JSONObject();
            msg.put("id",consultation.getHid());
            msg.put("name",userMapper.selectById(consultation.getUid()).getUsername());
            try {
                msg.put("time",timeUtil.getTimeDiff(consultation));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            msg.put("beginTime",consultation.getBeginTime());
            msg.put("rank",consultation.getCrank());
            res.add(msg);
        });
        return res;
    }
    /**
     * 咨询师根据访客姓名查找聊天记录
     */
    public JSONArray getConsultationsByName(int id,String name){
        JSONArray res = new JSONArray();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("uName",name);
        queryWrapper.like(StringUtils.isNotBlank(name), "uName", name);
        List<User> users = userMapper.selectList(queryWrapper);
        if (users.size() == 0){
           return res;
        }
        users.forEach(user -> {
            List<Consultation> consultations = consultationMapper.selectList(
                    new QueryWrapper<Consultation>().
                            eq("uid",user.getUserId()).
                            eq("cid",id));
            consultations.forEach(consultation -> {
                JSONObject msg = new JSONObject();
                msg.put("id",consultation.getHid());
                msg.put("name",user.getUsername());
                try {
                    msg.put("time",timeUtil.getTimeDiff(consultation));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                msg.put("beginTime",consultation.getBeginTime());
                msg.put("rank",consultation.getCrank());
                msg.put("averageRank",timeUtil.averageRank(consultations));
                res.add(msg);
            });
        });
        return res;
    }
    /**
     * 判断username是否有效
     */
    private boolean checkUsername(String username){
        QueryWrapper<Counselor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cUsername",username);
        return counselorMapper.selectList(queryWrapper).size() != 0;
    }
    /**
     *判断密码是否正确
     */
    private boolean checkPassword(int id,String password){
        QueryWrapper<LoginInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        return password.equals(loginInfoMapper.selectList(queryWrapper).get(0).getPassword());
    }
    /**
     * 获取最近四条聊天记录
     */
    public JSONArray lastConsultations(int cid) throws ParseException {
        JSONArray res = new JSONArray();
        QueryWrapper<Consultation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cid",cid);
        queryWrapper.orderByDesc("h_beginTime");
        queryWrapper.last("limit 4");
        List<Consultation> consultations = consultationMapper.selectList(queryWrapper);
        for (Consultation consultation: consultations) {
            JSONObject ret = new JSONObject();
            ret.put("id",consultation.getHid());
            ret.put("name",userMapper.selectById(consultation.getUid()).getUsername());
            Set<Consultation> temp = new HashSet<>();
            temp.add(consultation);
            String time = timeUtil.getTimeDiff(temp);
            ret.put("time",time);
            ret.put("beginTime",consultation.getBeginTime());
            //TODO 评级double
            ret.put("rank",consultation.getCrank());
            res.add(ret);
        }
        return res;
    }
    /**
     * 获取咨询师个人信息
     * 头像avatar，姓名name，
     * 性别gender，年龄age，身份证idNumber，电话phoneNum，邮箱email
     */
    public JSONObject getInfo(int id){
        Counselor counselor = counselorMapper.selectById(id);
        JSONObject ret = new JSONObject();
        ret.put("avatar",counselor.getProfilePhoto());
        ret.put("name",counselor.getName());
        ret.put("gender",counselor.getGender());
        ret.put("age",counselor.getAge());
        ret.put("idNumber",counselor.getIdNumber());
        ret.put("phoneNum",counselor.getPhoneNum());
        ret.put("email",counselor.getEmail());
        return ret;


    }
    /**
     * 获取在线且绑定的督导
     */
    public JSONArray getOnlineSupervisors(int id){
        JSONArray res = new JSONArray();
        supervisorBandCounselorMapper.selectList(
                new QueryWrapper<SupervisorBandCounselor>().eq("cid",id)).forEach(supervisorBandCounselor -> {
                    int sid = supervisorBandCounselor.getSid();
                    Supervisor supervisor = supervisorMapper.selectById(sid);
                    if (stateMapper.selectById(sid).getState() == 0){
                        JSONObject ret = new JSONObject();
                        ret.put("id",supervisor.getSid());
                        ret.put("name",supervisor.getName());
                        ret.put("avatar",supervisor.getProfilePhoto());
                        res.add(ret);
                    }
        });
        return res;
    }

}
